package com.example.clooweather;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.clooweather.gson.WeatherBean;
import com.example.clooweather.service.AutoUpdateService;
import com.example.clooweather.util.HttpUtil;
import com.example.clooweather.util.SunAnimationView;
import com.example.clooweather.util.WeatherImage;
import com.google.gson.Gson;

import java.io.IOException;
import java.sql.Time;
import java.util.Calendar;
import java.util.List;

import jp.wasabeef.glide.transformations.BlurTransformation;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {
    private ScrollView weatherLayout;
    private TextView titleCity;
    private TextView titleUpdateTime;
    private TextView degreeText;
    private TextView weatherInfoText;
    private LinearLayout forecastLayout;
    private TextView uvText;
    private TextView humText;
    private TextView comfortText;
    private TextView carWashText;
    private TextView sportText;
    private TextView dateText;
    private TextView infoText;
    private TextView maxText;
    private TextView minText;
    private TextView drsgText;
    private TextView travText;
    private TextView windDirText;
    private TextView windScText;
    private TextView windSpdText;
    private TextView flText;

    private ImageView bingPicImg;
    public SwipeRefreshLayout swipeRefresh;
    private String mWeatherId;
    public DrawerLayout drawerLayout;
    private Button navButton;
    private ImageView updateImage;
    private WeatherImage weatherImage = new WeatherImage();
    SunAnimationView sumView;
    private String mCurrentTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            //判断系统版本号 因为融合状态栏时Android5.0之后才有的 也就是5.0版本艺术上系统会执行后面的代码
            View decorView = getWindow().getDecorView();
            //调用getWindow().getDecorView();拿到当前活动的DecorView
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            //然后调用他的setSystemUiVisibility来改变系统UI的显示
            // View.SYSTEM_UI_FLAG_LAYOUT_STABLE|View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            //这两个参数就表示活动的布局会显示在状态栏上面
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            //setStatusBarColor最后调用这个方法来将状态栏设置为透明色
        }
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        //去标题
//        //requestWindowFeature(Window.FEATURE_NO_TITLE);如果这句话无法起到作用可以使用下面这句话去掉标题
//        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_weather);
        weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
        titleCity = (TextView) findViewById(R.id.title_city);
        titleUpdateTime = (TextView) findViewById(R.id.title_update_time);
        degreeText = (TextView) findViewById(R.id.degree_text);
        weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
        forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout);
        uvText = (TextView) findViewById(R.id.uv_text);
        humText = (TextView) findViewById(R.id.hum_text);
        comfortText = (TextView) findViewById(R.id.comfort_text);
        carWashText = (TextView) findViewById(R.id.car_wash_text);
        sportText = (TextView) findViewById(R.id.sport_text);
        bingPicImg = (ImageView) findViewById(R.id.bin_pic_img);
        drsgText = (TextView) findViewById(R.id.drsg_text);
        travText = (TextView) findViewById(R.id.trav_text);
        swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        navButton = (Button) findViewById(R.id.nav_button);
        updateImage = (ImageView) findViewById(R.id.now_image_view);
        windDirText = (TextView) findViewById(R.id.wind_dir_text);
        windScText = (TextView) findViewById(R.id.wind_sc_text);
        windSpdText = (TextView) findViewById(R.id.wind_spd_text);
        flText = (TextView) findViewById(R.id.fl_text);
        sumView = (SunAnimationView) findViewById(R.id.sun_view);


        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String weatherString = prefs.getString("weather", null);
        if (weatherString != null) {
            //有缓存的话直接解析天气数据
            Gson gson = new Gson();
            WeatherBean weatherBean = gson.fromJson(weatherString, WeatherBean.class);
            List<WeatherBean.HeWeather6Bean> weatherBeans = weatherBean.getHeWeather6();
            WeatherBean.HeWeather6Bean heWeather6Bean = weatherBeans.get(0);
            WeatherBean.HeWeather6Bean.BasicBean basicBean = heWeather6Bean.getBasic();
            mWeatherId = basicBean.getCid();
            showWeatherinfo(weatherBean);
        } else {
            //无缓存的时候去服务器查询天气
            mWeatherId = getIntent().getStringExtra("weather_id");
            weatherLayout.setVisibility(View.INVISIBLE);
            requestWeather(mWeatherId);
        }
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this);
                String temp = prefs.getString("weather_id", mWeatherId);
                requestWeather(temp);

            }
        });
        String binPic = prefs.getString("bing_pic", null);
        if (binPic != null) {
            Glide.with(WeatherActivity.this)
                    .load(binPic)
                    .bitmapTransform(new BlurTransformation(WeatherActivity.this, 15))
                    .into(bingPicImg);


        } else {
            loadBingPic();
        }
        navButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
    }


    private void loadBingPic() {
        //加载必应每日一图
        String requestBinPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBinPic, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String bingPic = response.body().string();
                //将返回的数据缓存到SharedPreferences中
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                editor.putString("bing_pic", bingPic);
                //向editor.putString添加数据
                editor.apply();
                //提交数据 editor.apply();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//
                        Glide.with(WeatherActivity.this)
                                .load(bingPic)
                                .bitmapTransform(new BlurTransformation(WeatherActivity.this, 15))
                                .into(bingPicImg);
                        //使用毛玻璃效果
                        //Glide加载图片的方法
                        // with 传入一个Content load传入网络图片的url地址 into传入想要设置的imageView的实例
                    }
                });
            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
        });

    }

    public void requestWeather(final String weatherId) {
        //https://free-api.heweather.com/s6/weather?location="+weatherId+"&key=dde9e47ec0f74c1297849627274108a7"
        String weatherUrl = "https://free-api.heweather.com/s6/weather?location=" + weatherId + "&key=dde9e47ec0f74c1297849627274108a7";
        //dde9e47ec0f74c1297849627274108a7
        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                Gson gson = new Gson();
                final WeatherBean weatherBean = gson.fromJson(responseText, WeatherBean.class);
                final List<WeatherBean.HeWeather6Bean> weatherBeans = weatherBean.getHeWeather6();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (weatherBeans != null && weatherBeans.size() > 0) {
//                            Log.d("JJJJJJJ",responseText);
                            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                            editor.putString("weather", responseText);
                            editor.apply();
                            showWeatherinfo(weatherBean);
                        } else {
                            Toast.makeText(WeatherActivity.this, "获取天气信息失败a !", Toast.LENGTH_LONG).show();
                        }
                        swipeRefresh.setRefreshing(false);
                    }
                });

            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WeatherActivity.this, "获取天气信息失败b", Toast.LENGTH_LONG).show();
                        swipeRefresh.setRefreshing(false);
                        //请求时间结束后还要swipeRefresh.setRefreshing(false);隐藏刷新进度条
                    }
                });
            }
        });
        loadBingPic();
    }

    private void showWeatherinfo(WeatherBean weatherBean) {
        List<WeatherBean.HeWeather6Bean> weatherBeans = weatherBean.getHeWeather6();
        WeatherBean.HeWeather6Bean heWeather6Bean = weatherBeans.get(0);
        WeatherBean.HeWeather6Bean.BasicBean basicBean = heWeather6Bean.getBasic();
        WeatherBean.HeWeather6Bean.UpdateBean updateBean = heWeather6Bean.getUpdate();
        WeatherBean.HeWeather6Bean.NowBean nowBean = heWeather6Bean.getNow();
        List<WeatherBean.HeWeather6Bean.DailyForecastBean> dailyForecastBean = heWeather6Bean.getDaily_forecast();
        List<WeatherBean.HeWeather6Bean.LifestyleBean> lifestyleBean = heWeather6Bean.getLifestyle();
        WeatherBean.HeWeather6Bean.DailyForecastBean dailytime = heWeather6Bean.getDaily_forecast().get(0);


        final Calendar mCalendar=Calendar.getInstance();
        int mHour=mCalendar.get(Calendar.HOUR_OF_DAY);
        //HOUR_OF_DAY24小时制的小时时间
        int mMinuts=mCalendar.get(Calendar.MINUTE);
        Log.d("QQQQQQQQ",String.valueOf(mHour)+String.valueOf(mMinuts));
        mCurrentTime = mHour+":"+mMinuts;
        sumView.setTimes(dailytime.getSr(),dailytime.getSs(), mCurrentTime);
        String cityName = basicBean.getLocation();
        String updateTime = updateBean.getLoc().split(" ")[1];
        String degree = nowBean.getTmp() + "℃";
        String weatherInfo = nowBean.getCond_txt();
        titleCity.setText(cityName);
        titleUpdateTime.setText("最近更新：" + updateTime);
        degreeText.setText(degree);
        weatherInfoText.setText(weatherInfo);

        int i = weatherImage.UpdateImage(weatherInfo);
        //调用WeatherImage的UpdateImage方法来设置天气图标  传入一个weatherInfo天气概况 返回一个天气图标的资源id

        updateImage.setImageResource(i);


        forecastLayout.removeAllViews();
        for (WeatherBean.HeWeather6Bean.DailyForecastBean daily : dailyForecastBean) {
            View view = LayoutInflater.from(this).inflate(R.layout.forecast_item,
                    forecastLayout, false);
            TextView dateText = (TextView) view.findViewById(R.id.date_text);
            TextView infotext = (TextView) view.findViewById(R.id.info_text);
            TextView maxText = (TextView) view.findViewById(R.id.max_text);
            TextView minText = (TextView) view.findViewById(R.id.min_text);
            dateText.setText(daily.getDate());
            //设置天气预报的日期
            infotext.setText(daily.getCond_txt_d());
            maxText.setText(daily.getTmp_max() + "℃");
            minText.setText(daily.getTmp_min() + "℃");
            forecastLayout.addView(view);
        }

        if (weatherBean.getHeWeather6() != null) {
            WeatherBean.HeWeather6Bean.DailyForecastBean daily = heWeather6Bean.getDaily_forecast().get(0);
            windDirText.setText(" " + nowBean.getWind_dir());
            windScText.setText(" " + nowBean.getWind_sc() + "级风");
            windSpdText.setText(" " + nowBean.getWind_spd() + "公里/小时");
            flText.setText(nowBean.getFl() + "℃");
            uvText.setText(daily.getUv_index());
            humText.setText(nowBean.getHum() + "%");
        }
        String comfort = "舒适度: " + lifestyleBean.get(0).getTxt();
        String carWash = "洗车建议: " + lifestyleBean.get(6).getTxt();
        String sport = "运动建议: " + lifestyleBean.get(3).getTxt();
        String drsg = "穿衣建议: " + lifestyleBean.get(1).getTxt();
        String trav = "旅游建议: " + lifestyleBean.get(4).getTxt();
        comfortText.setText(comfort);
        carWashText.setText(carWash);
        sportText.setText(sport);
        drsgText.setText(drsg);
        travText.setText(trav);

        /*
        * 将下拉条显示出来
        * */
        weatherLayout.setVisibility(View.VISIBLE);
        Intent intent = new Intent(this, AutoUpdateService.class);
        startService(intent);
    }

}
